package com.alibaba.citrus.cr.mn.order.center.facade.function.impl;

import com.alibaba.citrus.cr.common.exception.FunctionException;
import com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.OrderBizAssemble;
import com.alibaba.citrus.cr.mn.order.center.facade.function.common.AbstractOrderBizCreateService;
import com.alibaba.citrus.cr.mn.order.center.facade.function.common.OrderBizCreateService;
import com.alibaba.citrus.cr.mn.order.center.facade.function.convert.BeanConverter;
import com.alibaba.cz.base.tool.TenantUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.trace.TraceUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.mnordercenter.model.dto.*;
import com.epoch.app.mnordercenter.orderbaserequest.OrderAtomCreateResponse;
import com.epoch.app.mnordercenter.orderbaserequest.OrderLineAtomCreateResponse;
import com.epoch.app.mnordercenter.salesorderatom.service.SalesOrderAtomService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhangxiaorui
 * @ClassName SalesOrderBizCreateServiceImpl
 * @description: TODO
 * @date 2023/05/16 14:04
 * @version: 1.0
 */
@Service("salesOrderBizCreateService")
public class SalesOrderBizCreateServiceImpl extends AbstractOrderBizCreateService implements OrderBizCreateService<SalesOrderBizBatchCreateRequest, SalesOrderAtomBatchCreateRequest, OrderAtomCreateResponse> {
    private static final Log log = Log.getLogger(SalesOrderBizCreateServiceImpl.class);

    @Resource
    private SalesOrderAtomService salesOrderAtomService;

    @Resource
    private List<OrderBizAssemble<SalesOrderBizCreateRequest>> orderBizAssembles;

    @Override
    public void preHandleRequestParams(SalesOrderBizBatchCreateRequest bizBatchCreateRequest) {
        if (StringUtils.isBlank(bizBatchCreateRequest.getBusinessUnitCode())
                || StringUtils.isBlank(bizBatchCreateRequest.getBusinessType())
                || StringUtils.isBlank(bizBatchCreateRequest.getFromSys())) {
            return;
        }

        bizBatchCreateRequest.setOrderList(Optional.ofNullable(bizBatchCreateRequest.getOrderList()).orElse(Lists.newArrayList()));

        for (SalesOrderBizCreateRequest salesOrder : bizBatchCreateRequest.getOrderList()) {
            salesOrder.setBusinessUnitCode(bizBatchCreateRequest.getBusinessUnitCode());
            salesOrder.setBusinessType(bizBatchCreateRequest.getBusinessType());
            salesOrder.setFromSys(bizBatchCreateRequest.getFromSys());
            salesOrder.setReqNo(bizBatchCreateRequest.getReqNo());
        }
    }

    @Override
    public List<SalesOrderAtomCreateResponse> assembleBizBaseInfo(SalesOrderBizBatchCreateRequest bizOrderCreateList) {

        int totalSize = bizOrderCreateList.getOrderList().size();

        // 中心数据并行查询（eg：库存中心、商品中心、客户中心 等等）
//        CountDownLatch countDownLatch = new CountDownLatch(orderBizAssembles.size());

        Map<String, Object> queryResponseMap = Maps.newConcurrentMap();

        // 业务数据同步-校验&组装
        List<SalesOrderAtomCreateResponse> salesOrderAtomCreateFailResponses = Lists.newArrayList();

        try {
            String traceId = TraceUtil.getTraceId();
            String tenantId = TenantUtil.getTenantId();
            for (OrderBizAssemble<SalesOrderBizCreateRequest> orderBizAssemble : orderBizAssembles) {
//                ThreadPoolUtil.execute(() -> {
//                    try {
//                        TraceParam traceParam = new TraceParam();
//                        traceParam.setTraceId(traceId);
//                        traceParam.setTenantId(tenantId);
//                        CustomTraceThreadLocal.set(traceParam);
                        List<SalesOrderBizCreateRequest> orderList = bizOrderCreateList.getOrderList();
                        Map<String, Object> queryResult = orderBizAssemble.query(orderList);
                        queryResponseMap.putAll(queryResult);
//                    } finally {
//                        countDownLatch.countDown();
//                        // 清理当前子线程的traceId
//                        CustomTraceThreadLocal.clean();
//                    }
//                });
            }
//            countDownLatch.await();
        }catch (Exception e) {
            log.error("SalesOrderBizCreateServiceImpl#assembleBizBaseInfo await error", e);
            throw new RuntimeException(e);
        }

        log.info("SalesOrderBizCreateServiceImpl#assembleBizBaseInfo bizOrderCreateList:{}", JSON.toJSONString(bizOrderCreateList));
        Iterator<SalesOrderBizCreateRequest> iterator = bizOrderCreateList.getOrderList().iterator();
        while (iterator.hasNext()) {
            SalesOrderBizCreateRequest createRequest = iterator.next();
            // 按主单维度Order顺序进行数据组装
            for (OrderBizAssemble<SalesOrderBizCreateRequest> orderBizAssemble : orderBizAssembles) {
                // 数据组装校验失败时，跳出当前组装逻辑，进行下一主单数据组装
                Result<String> result = orderBizAssemble.assemble(queryResponseMap, createRequest);
                log.info("SalesOrderBizCreateServiceImpl#assembleBizBaseInfo createRequest={}, result={}", createRequest, result);
                if (!result.isSuccess()) {
                    addFailResponse(salesOrderAtomCreateFailResponses, result);
                    iterator.remove();
                    break;
                }
            }
        }

        assembleSalesOrderCreateCommonInfo(bizOrderCreateList);

        log.info("SalesOrderBizCreateServiceImpl#assembleBizBaseInfo totalSize={}, realSize={}", totalSize, bizOrderCreateList.getOrderList().size());

        return salesOrderAtomCreateFailResponses;
    }

    private static void addFailResponse(List<SalesOrderAtomCreateResponse> failResponses, Result<String> assembleResult) {

        if (StringUtils.contains(assembleResult.getResult(), "@")) {
            String[] resultInfoArr = assembleResult.getResult().split("@");
            String sourceOrderNo = resultInfoArr[0];
            String sourceLineNum = resultInfoArr[1];
            String productCode = resultInfoArr[2];

            SalesOrderAtomCreateResponse createResponse = new SalesOrderAtomCreateResponse();
            createResponse.setSourceOrderNo(sourceOrderNo);
            createResponse.setErrorCode("OC-01-001-01-16-007");
            createResponse.setMessage("销售订单批量创建整单失败");

            List<OrderLineAtomCreateResponse> orderDetails = Lists.newArrayList();
            OrderLineAtomCreateResponse lineResponse = new OrderLineAtomCreateResponse();
            lineResponse.setSourceLineNum(sourceLineNum);
            lineResponse.setProductCode(productCode);
            lineResponse.setErrorCode(assembleResult.getErrorCode());
            lineResponse.setMessage(assembleResult.getMessage());
            orderDetails.add(lineResponse);
            createResponse.setOrderDetails(orderDetails);
        } else {

            SalesOrderAtomCreateResponse response = new SalesOrderAtomCreateResponse();
            response.setSourceOrderNo(assembleResult.getResult());
            response.setErrorCode(assembleResult.getErrorCode());
            response.setMessage(assembleResult.getMessage());

            failResponses.add(response);
        }
    }

    @Override
    public SalesOrderAtomBatchCreateRequest convertAtomRequest(SalesOrderBizBatchCreateRequest createRequest) {
        log.info("SalesOrderBizCreateServiceImpl#convertAtomRequest createRequest:{}", JSON.toJSONString(createRequest));
        List<SalesOrderAtomCreateRequest> atomCreateRequests = Optional.ofNullable(createRequest.getOrderList())
                .orElse(Lists.newArrayList()).stream().map(order -> {

                    SalesOrderAtomCreateRequest atomCreateRequest = new SalesOrderAtomCreateRequest();
                    BeanConverter.convert(order, atomCreateRequest);

                    if (StringUtils.isBlank(atomCreateRequest.getFromSys())) {
                        atomCreateRequest.setFromSys(createRequest.getFromSys());
                    }
                    if (StringUtils.isBlank(atomCreateRequest.getBusinessType())) {
                        atomCreateRequest.setBusinessType(createRequest.getBusinessType());
                    }
                    if (StringUtils.isBlank(atomCreateRequest.getBusinessUnitCode())) {
                        atomCreateRequest.setBusinessUnitCode(createRequest.getBusinessUnitCode());
                    }

                    List<SalesOrderAtomCreateLineRequest> orderDetails = Optional.ofNullable(order.getOrderDetails())
                            .orElse(Lists.newArrayList()).stream().map(detail -> {
                                //子单dto对象未实现分层设计
                                SalesOrderAtomCreateLineRequest lineRequest = new SalesOrderAtomCreateLineRequest();
                                BeanConverter.convert(detail, lineRequest);
                                return lineRequest;
                            }).collect(Collectors.toList());

                    atomCreateRequest.setOrderDetails(orderDetails);

                    return atomCreateRequest;
                }).collect(Collectors.toList());

        SalesOrderAtomBatchCreateRequest atomBatchCreateRequest = new SalesOrderAtomBatchCreateRequest();
        atomBatchCreateRequest.setOrderList(atomCreateRequests);
        log.info("SalesOrderBizCreateServiceImpl#convertAtomRequest atomCreateRequests:{}", JSON.toJSONString(atomCreateRequests));
        return atomBatchCreateRequest;
    }

    @Override
    public List<OrderAtomCreateResponse> processAtomAbility(SalesOrderAtomBatchCreateRequest request, List<SalesOrderAtomCreateResponse> responses) {
        log.info("创建销售订单原子能力执行 Request={}", JSON.toJSONString(request));
        if (CollectionUtils.isEmpty(request.getOrderList())) {
            return convert(responses);
        }

        Result<List<SalesOrderAtomCreateResponse>> atomCreateResult = salesOrderAtomService.batchCreate(request);
        log.info("创建销售订单原子能力返回结果 Result={}",
                JSON.toJSONString(request), JSON.toJSONString(atomCreateResult));
        if (CollectionUtils.isNotEmpty(atomCreateResult.getResult())) {
            responses.addAll(atomCreateResult.getResult());
        } else {
            SalesOrderAtomCreateResponse response = new SalesOrderAtomCreateResponse();
            response.setErrorCode(atomCreateResult.getErrorCode());
            response.setMessage(atomCreateResult.getMessage());
            responses.add(response);
        }
        return convert(responses);
    }

    private List<OrderAtomCreateResponse> convert(List<SalesOrderAtomCreateResponse> responses) {
        if (CollectionUtils.isEmpty(responses)) {
            return Lists.newArrayList();
        }
        return responses.stream().map(p -> {
            OrderAtomCreateResponse response = new OrderAtomCreateResponse();
            BeanConverter.convert(p, response);
            return response;
        }).collect(Collectors.toList());
    }

}
